package com.xez.data
{
	import com.xez.util.FsConst;
	
	import flash.utils.ByteArray;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	/**
	 * Fs-Web-Dir-Img
	 * 
	 * @author Coco
	 */	
	public class FsRoot extends CacheData
	{
		public function FsRoot()
		{
			super();
		}
		
		[Bindable]
		public var webs:ArrayCollection;
		
		private var loaded:Boolean = false;
		
		override public function get cachename():String
		{
			return 'FsData';
		}
		
		public function load():void
		{
			if (loaded)
				return;
			
			loaded = true;
			
			if (hasCache())
				loadWebsFromCache();
			
			if (!webs || webs.length == 0)
				msg = '正在加载数据';
			
			loadWebsFromUrl();
		}
		
		public function refresh():void
		{
			msg = '正在刷新数据';
			loadWebsFromUrl();
		}
		
		private function loadWebsFromUrl():void
		{
			var hs:HTTPService = new HTTPService();
			hs.resultFormat = 'text';
			hs.addEventListener(ResultEvent.RESULT, getweb_resultHandler);
			hs.addEventListener(FaultEvent.FAULT, getweb_faultHandler);
			hs.url = FsConst.GET_WEB_URL;
			hs.method = 'POST';
			hs.send();
		}
		
		private function loadWebsFromCache():void
		{
			trace('从缓存读取网站数据');
			webs = new ArrayCollection();
			var webObjs:ArrayCollection;
			var bytes:ByteArray = getCache();
			
			if (bytes)
				webObjs	= getCache().readObject() as ArrayCollection;
			
			if (webObjs)
			{
				var web:WebRoot;
				for each (var webObj:Object in webObjs)
				{
					web = new WebRoot();
					web.name = webObj.name;
					web.isvip = webObj.isvip;
					webs.addItem(web);
				}
			}
		}
		
		private function getweb_resultHandler(e:ResultEvent):void
		{
			msg = null;
			
			trace('获取网站Result');
			
			var webxml:XML = new XML(e.result);
			trace('webxml', e.result);
			if (webxml)
			{
				webs = new ArrayCollection();
				var web:WebRoot;
				for (var i:int = 0; i < webxml.web.length(); i++)
				{
					// 设置网站数据
					web = new WebRoot();
					web.name = webxml.web[i].webname;
					web.isvip = webxml.web[i].isvip == '0' ? false : true;
					trace('发现网站', web.name);
					webs.addItem(web);
				}
				
				// 缓存数据
				var bytes:ByteArray = new ByteArray();
				bytes.writeObject(webs);
				saveCache(bytes);
			}
		}
		
		private function getweb_faultHandler(e:FaultEvent):void
		{
			trace('获取网站Fault');
			msg = null;
		}
		
	}
}